package com.offcn.filter;

import com.offcn.common.utils.JWTUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Component
public class InnerFilter extends AbstractGatewayFilterFactory<FilterConf> {

    public InnerFilter(){
        super(FilterConf.class);
    }

    @Override
    public GatewayFilter apply(FilterConf config) {

        return (((exchange, chain) -> {
            //允许执行
            //获取请求对象
            ServerHttpRequest request = exchange.getRequest();
            //获取响应对象
            ServerHttpResponse response = exchange.getResponse();
            //判断过滤器是否允许执行
            if(config.isIs()){

                //尝试从请求头获取令牌
                String token = request.getHeaders().getFirst("Authorization");
                //判断令牌是否为空
                if(!StringUtils.isEmpty(token)){
                    //调用令牌工具类，校验令牌
                    boolean verify = JWTUtil.verify(token);
                    //判断令牌是否为真
                    if(verify){
                        //令牌验证通过
                        //放行，继续转发到对应微服务
                        return chain.filter(exchange);
                    }else {

                        //令牌校验失败，响应一个错误json提示
                        Mono mono = returnFail(response);
                        return response.writeWith(mono);
                    }
                }
            }else {
                //自定义过滤器未启用，放行
                return chain.filter(exchange);

            }
            //令牌校验失败，响应一个错误json提示
            Mono mono = returnFail(response);
            return response.writeWith(mono);
        }));
    }

    //返回错误json提示
    private Mono returnFail(ServerHttpResponse response){
        //获取到响应头对象
        HttpHeaders headers = response.getHeaders();
        //在响应头设置响应文件类型，json
        headers.set("Content-Type","application/json; charset=UTF-8");
        //设置浏览器禁止缓存数据
        headers.set("Cache-Control","no-store, no-cache, must-revalidate, max-age=0");
        //准备一个响应内容
        String body="token验证失败";
        //包装成一个DataBuffer
        DataBuffer dataBuffer = response.bufferFactory().wrap(body.getBytes());
        //把DataBuffer设置到Mono
        return Mono.just(dataBuffer);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("is");
    }
}
